package com.webcamtracker.color.segmentation;


import com.webcamtracker.image.Color;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;


public class Segment {
    private List<Point> points;
    private Color color;
    private int id;
    private int sunWeightX = 0;
    private int sumWeightY = 0;

    private int x;
    private int y;
    private int width;
    private int height;

    public Segment(Color color, int id) {
        this.id = id;
        this.points = new ArrayList<Point>();
        this.color = color;
    }


    public Segment(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public int getId() {
        return id;
    }

    public void addPoint(Point point) {
        this.points.add(point);
        add(point.x, point.y);
        sunWeightX += point.x;
        sumWeightY += point.y;
    }

    private void add(int newx, int newy) {
        if ((width | height) < 0) {
            this.x = newx;
            this.y = newy;
            this.width = this.height = 0;
            return;
        }
        int x1 = this.x;
        int y1 = this.y;
        int x2 = this.width;
        int y2 = this.height;
        x2 += x1;
        y2 += y1;
        if (x1 > newx) x1 = newx;
        if (y1 > newy) y1 = newy;
        if (x2 < newx) x2 = newx;
        if (y2 < newy) y2 = newy;
        x2 -= x1;
        y2 -= y1;

        this.x = x1;
        this.y = y1;
        this.width = x2;
        this.height = y2;
    }


    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public List<Point> getPoints() {
        return points;
    }

    public Color getColor() {
        return color;
    }

    public String toString() {
        return "Points " + getPoints().size() + " - Id " + getId() + " Color " + getColor();
    }

    public Point getCog() {
        return new Point(sunWeightX / getPoints().size(), sumWeightY / getPoints().size());
    }

    public int getSize() {
        return getPoints().size();
    }

    public int getSunWeightX() {
        return sunWeightX;
    }

    public int getSumWeightY() {
        return sumWeightY;
    }
}
